package com.hong.demo.other.flink;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;

/**
 * 归纳聚合
 * 将当前元素与最后一次 reduce 得到的值归约(相加)，输出中间合并结果。
 * 将中间合并结果作为任务的一个状态保存起来，之后每来一个新的数据，就和之前的聚合状态进一步做归约(相加)。
 */
public class ReduceTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Integer> stream = env.fromCollection(Arrays.asList(1, 4, 6, 3, 2, 5));

        KeyedStream<Integer, Boolean> keyBy = stream.keyBy(number -> number > 3);

        SingleOutputStreamOperator<Integer> source = keyBy.reduce(new ReduceFunction<Integer>() {

            @Override
            public Integer reduce(Integer value1, Integer value2) throws Exception {
                System.out.println("value1 = " + value1 + " value2 = " + value2);
                // 将两个值相加
                return value1 + value2;
            }
        });

        source.print();

        env.execute();
    }
}
